package com.campus.client.view;

import com.campus.client.controller.TeacherCourseController;
import com.campus.client.net.ClientConnector;
import com.campus.common.vo.Classroom;
import com.campus.common.vo.Course;
import com.campus.common.vo.Student;
import com.campus.common.vo.User;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.*;

import java.util.List;

public class TeacherCourseView {

    private Accordion accordion;
    private ScrollPane scrollPane;
    private String queryKeyword;
    private User user;

    public enum CourseViewMode {
        ALL,        // 查询所有课程
        QUERY,      // 按关键字查询
        MYCOURSES   // 教师教授的课程
    }

    private CourseViewMode mode;

    public TeacherCourseView(CourseViewMode mode, User user) {
        this.mode = mode;
        this.user = user;
        accordion = new Accordion();
        initScrollPane();
        loadCourses();
    }

    public TeacherCourseView(CourseViewMode mode, String keyword, User user) {
        this.mode = mode;
        this.queryKeyword = keyword;
        this.user = user;
        accordion = new Accordion();
        initScrollPane();
        loadCourses();
    }

    public ScrollPane getView() {
        return scrollPane;
    }

    private VBox mainBox;

    private void initScrollPane() {
        mainBox = new VBox(0);
        mainBox.setFillWidth(true);

        accordion = new Accordion();
        accordion.setMaxWidth(Double.MAX_VALUE);

        // 表头 HBox
        HBox header = new HBox();
        header.getStyleClass().add("academic-course-header");
        header.setAlignment(Pos.CENTER_LEFT);
        header.setPadding(new Insets(4, 10, 4, 10));
        header.setSpacing(5);
        header.setMaxWidth(Double.MAX_VALUE);

        // 列：课程编号（固定宽）
        Label lblCourseId = new Label("课程编号");
        lblCourseId.setPrefWidth(140);
        lblCourseId.setAlignment(Pos.CENTER_LEFT);

        // 列：课程名称（自适应宽度）
        Label lblCourseName = new Label("课程名称");
        HBox.setHgrow(lblCourseName, Priority.ALWAYS);
        lblCourseName.setMaxWidth(Double.MAX_VALUE);
        lblCourseName.setAlignment(Pos.CENTER_LEFT);

        // 列：学分（固定宽）
        Label lblCredit = new Label("学分");
        lblCredit.setPrefWidth(80);
        lblCredit.setAlignment(Pos.CENTER);

        // 列：教学班个数（固定宽）
        Label lblClassCount = new Label("教学班个数");
        lblClassCount.setPrefWidth(100);
        lblClassCount.setAlignment(Pos.CENTER_RIGHT);

        header.getChildren().addAll(lblCourseId, lblCourseName, lblCredit, lblClassCount);
        mainBox.getChildren().addAll(header, accordion);

        scrollPane = new ScrollPane(mainBox);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
    }

    private void loadCourses() {
        try {
            String teacherId = user.getId();
            TeacherCourseController controller = new TeacherCourseController(new ClientConnector("172.20.10.2", 8888));

            List<Course> courses;
            switch (mode) {
                case ALL -> courses = controller.viewAllCourses();
                case MYCOURSES -> courses = controller.viewMyCourses(teacherId);
                case QUERY -> courses = controller.queryCourses(queryKeyword);
                default -> courses = List.of();
            }

            accordion.getPanes().clear();

            if (courses == null || courses.isEmpty()) {
                Label emptyLabel = new Label("没有找到课程");
                TitledPane pane = new TitledPane("提示", emptyLabel);
                pane.getStyleClass().add("custom-titled-pane");
                accordion.getPanes().add(pane);
                return;
            }

            for (Course course : courses) {
                TitledPane pane = new TitledPane();
                pane.setCollapsible(true);
                pane.setExpanded(false);
                pane.getStyleClass().add("custom-titled-pane");

                // 课程行
                HBox courseRow = new HBox(0);
                courseRow.getStyleClass().add("course-row");
                courseRow.setPadding(new Insets(5,10,5,10));
                courseRow.setAlignment(Pos.CENTER_LEFT);

                VBox courseIdColumn = new VBox(2);
                courseIdColumn.setPrefWidth(140);

                Label lblCourseId = new Label(course.getCourseId());
                lblCourseId.setAlignment(Pos.CENTER_LEFT);

                Label detailLink = new Label("课程详情");
                detailLink.getStyleClass().add("detail-link");
                detailLink.setStyle("-fx-text-fill: #1a73e8; -fx-underline: true;");
                detailLink.setOnMouseClicked(e -> pane.setExpanded(!pane.isExpanded()));

                courseIdColumn.getChildren().addAll(lblCourseId, detailLink);

                Label lblCourseName = new Label(course.getCourseName());
                HBox.setHgrow(lblCourseName, Priority.ALWAYS);
                lblCourseName.setMaxWidth(Double.MAX_VALUE);

                Label lblCredit = new Label(String.valueOf(course.getCredit()));
                lblCredit.setPrefWidth(80);
                lblCredit.setAlignment(Pos.CENTER);

                Label lblClassCount = new Label(String.valueOf(course.getClassrooms().size()));
                lblClassCount.setPrefWidth(100);
                lblClassCount.setAlignment(Pos.CENTER_RIGHT);

                courseRow.getChildren().addAll(courseIdColumn, lblCourseName, lblCredit, lblClassCount);

                pane.setGraphic(courseRow);

                // 班级卡片
                FlowPane classContainer = new FlowPane();
                classContainer.setHgap(10);
                classContainer.setVgap(10);
                classContainer.setPadding(new Insets(5,10,10,10));

                for (Classroom c : course.getClassrooms()) {
                    VBox card = new VBox(8);
                    card.getStyleClass().add("card");
                    Label lblId = new Label("班级编号: " + c.getClassId());
                    Label lblTimeLoc = new Label("时间地点: " + c.getCourseTime() + " @" + c.getCourseLocation());
                    Label lblCapacity = new Label("人数/容量: " + c.getSelectedCount() + "/" + c.getCapacity());
                    Label lblType = new Label("班级性质: " + (c.getClassType() != null ? c.getClassType() : "未设置"));

                    HBox btnBox = new HBox(5);
                    btnBox.getStyleClass().add("bottom-row");
                    Button btnStudents = new Button("查看学生名单");
                    btnStudents.getStyleClass().add(".transparent-button");
                    btnStudents.setOnAction(e -> {
                        try {
                            List<Student> students = controller.viewStudentsInClass(c.getClassId());
                            showStudentsDialog(c.getClassId(), students);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    });
                    btnBox.getChildren().add(btnStudents);

                    card.getChildren().addAll(lblId, lblTimeLoc, lblCapacity, lblType, btnBox);
                    classContainer.getChildren().add(card);
                }

                pane.setContent(classContainer);

                // 绑定宽度自适应
                courseRow.prefWidthProperty().bind(scrollPane.widthProperty().subtract(20));
                courseRow.maxWidthProperty().bind(scrollPane.widthProperty().subtract(20));

                accordion.getPanes().add(pane);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showStudentsDialog(String classId, List<Student> students) {
        TableView<Student> table = new TableView<>();
        TableColumn<Student,String> colId = new TableColumn<>("学号");
        colId.setCellValueFactory(cd -> new javafx.beans.property.SimpleStringProperty(cd.getValue().getStudentId()));
        colId.setPrefWidth(150);
        TableColumn<Student,String> colName = new TableColumn<>("姓名");
        colName.setCellValueFactory(cd -> new javafx.beans.property.SimpleStringProperty(cd.getValue().getStudentName()));
        colName.setPrefWidth(150);

        table.getColumns().addAll(colId, colName);
        if(students != null) table.getItems().addAll(students);

        Dialog<Void> dialog = new Dialog<>();
        dialog.setTitle("班级 " + classId + " 学生名单");
        DialogPane pane = new DialogPane();
        pane.setContent(table);
        pane.getButtonTypes().add(ButtonType.CLOSE);
        dialog.setDialogPane(pane);
        dialog.showAndWait();
    }
}
